package com.fg.cloud.agency.controller.system;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fg.cloud.agency.controller.BaseAgencyController;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.finals.Agency;
import com.fg.cloud.common.finals.UserType;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;
import com.fg.cloud.manager.entry.system.TrolleyEntity;
import com.fg.cloud.manager.entry.system.vo.AgencyCartVo;
import com.fg.cloud.manager.service.agency.AgencyCartService;

@Controller
@RequestMapping("/agencyCart")
public class AgencyCartController extends BaseAgencyController {

	@Autowired
	private AgencyCartService agencyCartService;
	
	
	/**
	 * Description:添加商品至购物车
	 * @param req
	 * @param resp
	 * @param sku sku实体
	 * @param amount 购买数量
	 * @param unit 购买商品单位
	 * @param stdAmount 单位换算数量
	 * @author dingjiang
	 * @date 2017年8月31日下午1:30:40
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/insert",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void insert(HttpServletRequest request, HttpServletResponse resp, 
			AgencyCartVo entity, Long productId, Long skuId) {
		try {
			/*ProductInfoVo entity = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(product), ProductInfoVo.class);
			agencyCartService.insert(entity, user);*/
			if (null == entity || null == skuId) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "缺少待添加购物车商品");
				return;
			}
			boolean flag = false;
			
			//将传参的skuId 设置到正确位置
			entity.setSkuId(skuId);
			entity.setId(null);
			entity.setProductId(productId);
			//将价格设置到正确位置
			//entity.setPromotionPrice(entity.getSpecialPrice());
			AgencyUserVo user = getCurrentAgencyUser();
			entity.setAgeId(user.getAgeId());
			//判断amount是否为空,若为空,数量加1
			if (null == entity.getAmount()) entity.setAmount(BigDecimal.ONE);
			//判断是否手工录入价格
			if (null == entity.getIsCustom()) entity.setIsCustom(0);
			//判断加入进来的是否是标准产品,若不是则将spec清空
			if (0 == entity.getIsStandard()) entity.setProductSpec(null);
			
			//判断要添加的商品skuId和unitId是否已存在，存在就只更新数量
			if (agencyCartService.filter(entity)) {
				flag = agencyCartService.addAmount(entity, user.getId());
				doResult(resp, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, 
						null, flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
				return;
			}
			
			setCreateInfo(entity, request);
			setUpdateInfo(entity, request);
			entity.setFacId(user.getFacId());
			entity.setAgeId(user.getAgeId());
			flag = agencyCartService.insertSelective(entity);
			
			doResult(resp, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, 
					null, flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAC_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:基础购物车快捷提醒
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年8月29日上午9:29:59
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/baseCart",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void baseCart(HttpServletRequest req, HttpServletResponse resp){
		try {
			PageUtils<AgencyCartVo> pageInfo = new PageUtils<>(1, 10);
			AgencyUserVo user = getCurrentAgencyUser();
			Map<String, Object> condition = pageInfo.getCondition();
			condition.put("ageId", user.getAgeId());
			condition.put("facId", user.getFacId());
			pageInfo.setTablename(Agency.getTableName(user.getFacId()));
			
			agencyCartService.findList(pageInfo, user);
			doResult(resp, true, StatusCode.FINDSUCCESS, pageInfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:点击去购物车
	 * @param req
	 * @param resp
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @author dingjiang
	 * @date 2017年8月29日上午8:57:00
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/selectByPage",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void selectByPage(HttpServletRequest req, HttpServletResponse resp,
			Integer page, Integer rows, String sort, String order){
		try {
			if (null == page) page = 1;
			if (null == rows) rows = 10;
			PageUtils<AgencyCartVo> pageInfo = new PageUtils<AgencyCartVo>(
					page, rows, sort, order);
			AgencyUserVo user = getCurrentAgencyUser();
			Map<String, Object> condition = pageInfo.getCondition();
			condition.put("ageId", user.getAgeId());
			condition.put("facId", user.getFacId());
			pageInfo.setTablename(Agency.getTableName(user.getFacId()));
			
			//处理价格排序问题
			if ("promotionPrice".equals(sort)) {
				pageInfo.setOrders(pageInfo.getOrders().concat(",").
						concat("sellPrice ").concat(order));
			}
			
			agencyCartService.findList(pageInfo, user);
			doResult(resp, true, StatusCode.FINDSUCCESS, pageInfo, ResultType.FIND_SUCCESS);		
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:修改商品数量
	 * @param req
	 * @param resp
	 * @param entity
	 * @author dingjiang
	 * @date 2017年8月29日下午3:01:29
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/modifyAmount",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void modifyAmount(HttpServletRequest req, HttpServletResponse resp, AgencyCartVo entity){
		try {
			//验证非空
			if ( LongUtils.isEmpty(entity.getId()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.INPUT_NULL);
				return ;
			}
			if ( null == entity.getAmount() ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.INPUT_NULL);
				return ;
			}
			entity.setUpdater(getCurrentAgencyUser().getId());
			agencyCartService.updateByPrimaryKeySelective(entity);
			doResult(resp, true, StatusCode.DEFAULT, null, ResultType.SAVE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	

	/**
	 * Description:提交订单前的商品信息校验
	 * @param req
	 * @param resp
	 * @param orderInfo
	 * @author dingjiang
	 * @date 2017年9月4日上午9:31:05
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/selectNew",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void selectNew(HttpServletRequest req, HttpServletResponse resp, List<TrolleyEntity> trolleys){
		/*try {
			List<OrderDetailVo> listDetails = new ArrayList<OrderDetailVo>();//定义返回订单详情对象的集合
			AgencyUserVo currentAgencyUser = getCurrentAgencyUser();//获取当前经销商用户
			BigDecimal multiply = currentAgencyUser.getDiscount().multiply(BigDecimal.valueOf(0.01));//经销商等级折扣
			boolean stockFlag = false;
			boolean priceFlag = false;
			String stockStr = "【 ";
			String priceStr = "【 ";
			
			//获取前端的skuId集合
			List<Long> skuids = new ArrayList<Long>();
			if ( trolleys.size() != 0 ) 
				for (int i = 0; i < trolleys.size(); i++) skuids.add(trolleys.get(i).getSkuId());
			
			//通过与数据库交互，获取最新的sku集合
			List<ProductSkuEntity> skus = new ArrayList<ProductSkuEntity>();
			List<List<Long>> splitList = DefaultListUtils.splitList(skuids, 15);
			for (List<Long> list : splitList) {
				System.out.println(list);
				//根据当前skuId集合查询对应的sku集合
				List<ProductSkuEntity> skuEntities = agencyCartService.selectNewPrice(list);
				skus.addAll(skuEntities);	
			}
			
			//判断库存是否充足，价格是否有变动，并同步最新价格和商品购买精度
			for (int i = 0; i < skus.size(); i++) {
				ProductSkuEntity newSku = skus.get(i);
				//计算当条商品总数量
				Double totalAmount = trolleys.get(i).getAmount().doubleValue() * trolleys.get(i).getStdAmount();
				//判断该商品的库存是否充足
				if( newSku.getStock() < totalAmount && 0 == currentAgencyUser.getStockSetup().getZeroFlag() ){
					stockFlag = true;
					stockStr = stockStr.concat( ((Integer)(i+1)).toString() ).concat("."+trolleys.get(i).getProductName()+" ");	
				}
				//判断该商品价格是否有变动
				if ( !trolleys.get(i).getPromotionPrice().equals(newSku.getProductPrice().multiply(multiply)) ) {
					priceFlag = true;
					priceStr = priceStr.concat( ((Integer)(i+1)).toString() ).concat("."+trolleys.get(i).getProductName()+" ");
					listDetails.get(i).setPromotionPrice(newSku.getProductPrice().multiply(multiply));//同步订单价格
				}
				//同步商品购买精度
				listDetails.get(i).setPrecision(newSku.getPrecision());
			}
			
			//这是库存不足的情况
			if ( stockFlag ) {
				doResult(resp, false, StatusCode.SAVEERROR, stockStr.concat("】"), "库存不足，无法下单！");
				return ;
			}
			//这是价格变动的情况
			if ( priceFlag ) {
				doResult(resp, false, StatusCode.SAVEERROR, priceStr.concat("】"), "商品价格已更新，订单价格异常！");
				return ;
			}
			
			//给前端返回一个订单详情集合
			doResult(resp, true, StatusCode.SAVESUCCESS, listDetails, ResultType.SAVE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}*/
	}
	
	/**
	 * Description:判断一个数组中是否包含某个元素
	 * @param arr
	 * @param targetValue
	 * @return
	 * @author dingjiang
	 * @date 2017年8月30日上午9:01:52
	 */
	public static boolean useList(Long[] arr, Long targetValue) {
	    return Arrays.asList(arr).contains(targetValue);
	}
	
	/**
	 * Description:删除指定的购物车记录
	 * @param req
	 * @param resp
	 * @param ids
	 * @author dingjiang
	 * @date 2017年8月30日上午10:41:37
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/delete",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void delete(HttpServletRequest req, HttpServletResponse resp, String ids){
		try {
			if (StringUtils.isEmpty(ids) || ids.length() < 1) {
				doResult(resp, false, StatusCode.REMOVEERROR, null, "缺少删除项");
				return;
			}
			boolean flag = agencyCartService.deletes(getCurrentAgencyUser().getAgeId(), 
					LongUtils.convert(ids.split(",")));
			doResult(resp, flag, flag ? StatusCode.REMOVESUCCESS : StatusCode.REMOVEERROR, 
					null, flag ? ResultType.REMOVE_SUCCESS : ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.REMOVEERROR, null, e.getMessage());
		}
	}
	
	
	/**
	 * Description:根据skuId删除购物车记录
	 * @param req
	 * @param resp
	 * @param ids
	 * @author dingjiang
	 * @date 2017年9月25日上午10:11:12
	 */
	public void deleteBySku(HttpServletRequest req, HttpServletResponse resp, String ids){
		try {
			if (StringUtils.isEmpty(ids) || ids.length() <= 1) {
				doResult(resp, false, StatusCode.REMOVEERROR, null, "缺少删除项");
				return;
			}
			boolean flag = agencyCartService.deleteBySku(getCurrentAgencyUser().getAgeId(), 
					LongUtils.convert(ids.split(",")));
			doResult(resp, flag, flag ? StatusCode.REMOVESUCCESS : StatusCode.REMOVEERROR, 
					null, flag ? ResultType.REMOVE_SUCCESS : ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.REMOVEERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:清空购物车
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年8月30日上午11:11:52
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/empty",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void empty( HttpServletRequest req, HttpServletResponse resp ){
		try {
			boolean flag = agencyCartService.deleteAll(getCurrentAgencyUser().getAgeId());
			doResult(resp, flag, flag ? StatusCode.REMOVESUCCESS : StatusCode.REMOVEERROR, 
					null, flag ? ResultType.REMOVE_SUCCESS : ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.REMOVEERROR, null, e.getMessage());
		}
	}
	
}
